package com.exteam.common.util;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.provider.MediaStore;
import android.provider.MediaStore.Audio.Media;
import android.provider.MediaStore.Video.Thumbnails;
import android.provider.MediaStore.Video.VideoColumns;
import android.view.View;
import android.view.View.MeasureSpec;

import java.io.File;
import java.io.IOException;

/**
 * Created by jianan on 2015/6/9.
 * 媒体工具
 */
public class MultiMediaUtils {
    // 调用系统摄像头拍摄
    public static void openPicture(Activity currAct, int requestCode) {

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        currAct.startActivityForResult(intent, requestCode);
    }

    // 调用系统图库
    public static void selectPicture(Activity currAct, int requestCode) {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);//ACTION_OPEN_DOCUMENT
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("image/*");
        currAct.startActivityForResult(intent, requestCode);
        //if(android.os.Build.VERSION.SDK_INT>=android.os.Build.VERSION_CODES.){
        // 4.4
        //currAct.startActivityForResult(intent, SELECT_PIC_KITKAT);
        //}else{
        //currAct.startActivityForResult(intent, requestCode);
        //}
    }

    // 计算图片比例缩小
    public static int computeSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) {
        int initialSize = computeInitialSampleSize(options, minSideLength, maxNumOfPixels);
        int roundedSize;
        if (initialSize <= 8) {
            roundedSize = 1;
            while (roundedSize < initialSize) {
                roundedSize <<= 1;
            }
        } else {
            roundedSize = (initialSize + 7) / 8 * 8;
        }
        return roundedSize;
    }

    private static int computeInitialSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) {
        double w = options.outWidth;
        double h = options.outHeight;
        int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));
        int upperBound = (minSideLength == -1) ? 128 : (int) Math.min(Math.floor(w / minSideLength), Math.floor(h / minSideLength));
        if (upperBound < lowerBound) {
            // return the larger one when there is no overlapping zone.
            return lowerBound;
        }
        if ((maxNumOfPixels == -1) && (minSideLength == -1)) {
            return 1;
        } else if (minSideLength == -1) {
            return lowerBound;
        } else {
            return upperBound;
        }
    }

    // 获取图片的元数据（包含日期、日期时间、空间信息（经纬度、高度）、Camera信息（孔径、焦距、旋转角、曝光量等等）。
    public static ExifInterface getImageExif(String imgpath) {
        ExifInterface exif = null;
        try {
            exif = new ExifInterface(imgpath);
        } catch (IOException e) {
            e.printStackTrace();
            exif = null;
        }
        return exif;
    }

    // 获取图片角度
    public static int getImageDigree(String imgpath) {
        ExifInterface exif = null;
        int digree = 0;
        try {
            exif = new ExifInterface(imgpath);

            if (exif != null) {
                // 读取图片中相机方向信息
                int ori = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                        ExifInterface.ORIENTATION_UNDEFINED);
                // 计算旋转角度
                switch (ori) {
                    case ExifInterface.ORIENTATION_ROTATE_90:
                        digree = 90;
                        break;
                    case ExifInterface.ORIENTATION_ROTATE_180:
                        digree = 180;
                        break;
                    case ExifInterface.ORIENTATION_ROTATE_270:
                        digree = 270;
                        break;
                    default:
                        digree = 0;
                        break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            exif = null;
        }
        return digree;
    }

    public static Bitmap getBitmapByView(View view) {

        view.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
        view.buildDrawingCache();
        return view.getDrawingCache();
    }

    // 加载图片，是否旋转
    public static Bitmap rotateBitmap(Bitmap bm, int digree) {
        if (digree != 0) {
            // 旋转图片
            Matrix m = new Matrix();
            m.postRotate(digree);
            bm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(),
                    bm.getHeight(), m, true);
        }
        return bm;
    }


    // 加载图片，是否旋转
    public static Bitmap loadBitmap(String imgpath, boolean isRotate) {

        Bitmap bm = BitmapFactory.decodeFile(imgpath);
        if (!isRotate) {
            return bm;
        }
        ExifInterface exif = getImageExif(imgpath);
        int digree = 0;
        if (exif != null) {
            // 读取图片中相机方向信息
            int ori = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_UNDEFINED);
            // 计算旋转角度
            switch (ori) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    digree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    digree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    digree = 270;
                    break;
                default:
                    digree = 0;
                    break;
            }
        }
        if (digree != 0) {
            // 旋转图片
            Matrix m = new Matrix();
            m.postRotate(digree);
            bm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(),
                    bm.getHeight(), m, true);
        }
        return bm;
    }

    // 调用系统摄像头拍摄
    public static void openVideo(Activity currAct, int requestCode) {

        Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
        currAct.startActivityForResult(intent, requestCode);
    }

    // 调用系统视频数据
    public static void selectVideo(Activity currAct, int requestCode) {

        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);//ACTION_OPEN_DOCUMENT
        //intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("video/*");
        currAct.startActivityForResult(intent, requestCode);
    }

    // 生成视频缩略图
    public static Bitmap createVideoThumbnail(String videoPath) {
        Bitmap bitmap = ThumbnailUtils.createVideoThumbnail(videoPath, Thumbnails.MICRO_KIND);
        return bitmap;
    }

    // 通过ContentResoler得到视频资源，返回资源路径
    public static File getVideoFile(Uri videoUri, Context ctx) {

        File localFile = null;
        try {
            Cursor cursor = ctx.getContentResolver().query(videoUri, null, null,
                    null, null);
            if (cursor != null && cursor.moveToNext()) {
                int id = cursor.getInt(cursor.getColumnIndex(VideoColumns._ID));
                String filePath = cursor.getString(cursor.getColumnIndex(VideoColumns.DATA));
                localFile = new File(filePath);
                // 以后可以缓存到缓存目录
                cursor.close();
            }

        } catch (Exception e) {
            // TODO Auto-generated catch block
            CommLogger.d("getVideoFile" + e.toString());
        }
        return localFile;
    }

    // 调用系统录音数据
    public static void selectAudio(Activity currAct, int requestCode) {

        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);//ACTION_OPEN_DOCUMENT
        //intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("audio/*");
        //intent.putExtra("return-data", true);
        currAct.startActivityForResult(intent, requestCode);
    }

    public static void openAudio(Activity currAct, int requestCode) {
        Intent intent = new Intent(Media.RECORD_SOUND_ACTION);
        currAct.startActivityForResult(intent, requestCode);
    }

    public static int computeWidthHeight(BitmapFactory.Options options, int widthOffset, int heightOffset) {
        int imageHeight = options.outHeight;
        int imageWidth = options.outWidth;
        int screenW = ScreenUtils.getScreenWidth(CommUtils.getContext());
        int screenH = ScreenUtils.getScreenHeight(CommUtils.getContext());
        if (imageWidth > screenW / widthOffset) {
            imageWidth = screenW / widthOffset;
        }
        if (imageHeight > screenH / heightOffset) {
            imageHeight = screenH / heightOffset;
        }
        return imageWidth * imageHeight;
    }

    public static Bitmap getPictureBitmap(File localFile, int widthOffset, int heightOffset) {
        Bitmap bitmap = null;
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(localFile.getAbsolutePath(), options);
        CommLogger.d("old: w:" + options.outWidth + " h:" + options.outHeight);
        options.inSampleSize = MultiMediaUtils.computeSampleSize(options, -1, computeWidthHeight(options, widthOffset, heightOffset));
        options.inJustDecodeBounds = false;
        bitmap = BitmapFactory.decodeFile(localFile.getAbsolutePath(), options);
        CommLogger.d("new: w:" + options.outWidth + " h:" + options.outHeight);
        return bitmap;
    }


}
